// ActionScript file
import awardBlankSheet.AwardBlankGrid;

import common.commonFunction;

import mx.collections.ArrayCollection;
import mx.controls.AdvancedDataGrid;
import mx.controls.Alert;
import mx.controls.advancedDataGridClasses.AdvancedDataGridColumn;
import mx.managers.PopUpManager;
import mx.rpc.events.ResultEvent;


[Bindable]
private var statusXml:XML;
[Bindable]
private var pendingXml:XML;
private var entityId:String=null;
private var programId:String=null;
private var entityType:String=null;
private var branchId:String=null;
private var specializationId:String=null;
private var semesterId:String=null;
private var courseCode:String=null;
private var courseName:String=null; //added by ankit
private var sessionStartDate:String=null;
private var sessionEndDate:String=null;

private var entityName:String=null; //added by ankit
private var programName:String=null; //added by ankit
private var branchName:String=null; //added by ankit
private var specializationName:String=null; //added by ankit
private var semesterName:String=null; //added by ankit
private var entityTypeName:String=null; //added by ankit

public var awardBlankGrid:AwardBlankGrid=new AwardBlankGrid();
public var pendingList:PendingRequest;
[Embed(source="images/success.png")]private var successIcon:Class;	
[Embed(source="images/error.png")]private var errorIcon:Class;
[Embed(source="images/warning.png")]private var warningIcon:Class;

/**
 * function for setting value of button
 */
private function setButtonPressed(status:String):void{
buttonPressed=status;
}
	
	/**
	 * function for setting values for variables based on selections
	 */
	private function setVariables():void{
		if(buttonPressed=='SW'){
			if(Validator.validateAll([entityTypeValidator,entityNameValidator,programValidator,branchValidator,
				specializationValidator,semesterValidator,courseCodeValidator]).length==0){
				entityId=entityXml.root.(name==entityNameCombo.selectedLabel).code;
				entityType=entityTypeXml.entityTypeList.(entity_name==entityTypeCombo.selectedLabel).entity_id;
				programId=programXml.root.(name==programCombo.selectedLabel).code;
				branchId=branchXml.root.(name==branchCombo.selectedLabel).code;
				specializationId=specXml.root.(name==specializationCombo.selectedLabel).code;
				semesterId=semXml.root.(name==semesterCombo.selectedLabel).code;
				courseCode=courseCodeCombo.selectedLabel;
				sessionStartDate=semXml.root.(name==semesterCombo.selectedLabel).startDate;
				sessionEndDate=semXml.root.(name==semesterCombo.selectedLabel).endDate;
				getEvaluationComponents();
			}
		}
		else if(buttonPressed=='PL'){
			if(pendingList.pendingListGrid.selectedItems.length>0){
				entityId=pendingList.pendingListGrid.selectedItem.entityId;
				entityType=pendingList.pendingListGrid.selectedItem.entityType;
				programId=pendingList.pendingListGrid.selectedItem.programId;
				branchId=pendingList.pendingListGrid.selectedItem.branchId;
				specializationId=pendingList.pendingListGrid.selectedItem.specializationId;
				semesterId=pendingList.pendingListGrid.selectedItem.semesterCode;
				courseCode=pendingList.pendingListGrid.selectedItem.courseCode;
				sessionStartDate=pendingList.pendingListGrid.selectedItem.startDate;
				sessionEndDate=pendingList.pendingListGrid.selectedItem.endDate;
				entityName=pendingList.pendingListGrid.selectedItem.entityName; //added by ankit
				entityTypeName=pendingList.pendingListGrid.selectedItem.entityTypeName; //added by ankit
				programName=pendingList.pendingListGrid.selectedItem.programName; //added by ankit
				branchName=pendingList.pendingListGrid.selectedItem.branchName; //added by ankit
				specializationName=pendingList.pendingListGrid.selectedItem.specializationName; //added by ankit
				semesterName=pendingList.pendingListGrid.selectedItem.semesterName; //added by ankit
				courseName=pendingList.pendingListGrid.selectedItem.courseName; //added by ankit
			    getEvaluationComponents();
			}else{
				Alert.show(commonFunction.getMessages('pleaseSelectAtleastOneRecord'),commonFunction.getMessages('error'),4,null,null,warningIcon);
			}
		}
	}


	/**
	 * function for enabling/disabling buttons according to status
	 */
	private function resultHandler_Status(event:ResultEvent):void{
		statusXml=event.result as XML;
//	   	Alert.show("checkStatus"+statusXml);
	  	var status:String=statusXml.exception.exceptionstring;
		switch(status+""){
			case 'WDW': submitForApprovalButton.enabled=true;
		  				saveButton.enabled=true;	
		  				withdrawButton.enabled=false;
		  				approveButton.enabled=false;
		  				rejectButton.enabled=false;
		  				break;
		  	case 'SUB': withdrawButton.enabled=true;
		  				submitForApprovalButton.enabled=false;
		  				saveButton.enabled=false;	
		  				approveButton.enabled=false;
		  				rejectButton.enabled=false;
		  				break;	
		  	case 'APR': withdrawButton.enabled=false;
		  				submitForApprovalButton.enabled=false;
		  				saveButton.enabled=false;
		  				approveButton.enabled=false;
		  				rejectButton.enabled=false;
		  				break;	  				
		  	default:   submitForApprovalButton.enabled=true;
		  				saveButton.enabled=true;
		  				withdrawButton.enabled=false;
		  				approveButton.enabled=false;
		  				rejectButton.enabled=false;
		  				break;
		  }
	}
 
 [Bindable]public var pendingAC:ArrayCollection;
	 /**
	 * function for getting list of pending requests
	 */
	 private function resultHandler_PendingList(event:ResultEvent):void{
	 	pendingXml=event.result as XML;
	   	pendingAC=new ArrayCollection();
		var flag:Boolean=true;
	   	for each (var object:Object in pendingXml.root){
	   		pendingAC.addItem({courseName:object.courseName,courseCode:object.courseCode,
	   		entityId:object.entityId,entityType:object.entityType,programId:object.programId,
	   		branchId:object.branchId,specializationId:object.specializationId,semesterCode:object.semesterCode,
	   		startDate:object.startDate,endDate:object.endDate, entityName:object.entityName, entityTypeName:object.entityTypeName,
	   		programName:object.programName, branchName:object.branchName, specializationName:object.specializationName, 
	   		semesterName:object.semesterName});
	   	}
	   	
	   	if(pendingAC.length>0)
	   	{
	   		showPendingButton.visible=true;
	   	}
	   	else
	   	{
	   		showPendingButton.visible=false;
	   	}
	 } 
 
 
	 /**
	 * function for submitting award sheet for approval
	 */
	private function submitSheet():void{
	 	var params:Object=new Object();
	 	params["courseCode"]=courseCode;
		params["startDate"]=semXml.root.(name==semesterCombo.selectedLabel).startDate;
		params["endDate"]=semXml.root.(name==semesterCombo.selectedLabel).endDate;
	    params["programCourseKey"]=programCourseKey;
	    params["entityId"]=entityId;
	    params["employeeCode"]=employeeCode;  
	    params["status"]='SUB';
		params["displayType"]=displayType;
	    httpSubmitApprovalRequest.send(params);
	 }
 
	 /*
	 * request handler for submit button
	 */
	 private function resultHandler_Submit(event:ResultEvent):void{
	 	var result:XML=event.result as XML;
		if(result.exception.exceptionstring == 'E'){
	   		Alert.show(commonFunction.getMessages('error'),commonFunction.getMessages('error'),4,null,null,errorIcon);
		}
		else{
	  		saveButton.enabled=false;   
	   		submitForApprovalButton.enabled=false;
	   		Alert.show(commonFunction.getMessages('success'),commonFunction.getMessages('success'),4,null,null,successIcon);
	   	}
	 }
 
 
	 /*
	 * request handler for withdraw button
	 */
	private function resultHandler_Withdraw(event:ResultEvent):void{
		var result:XML=event.result as XML;
		if(result.exception.exceptionstring == 'E'){
	   		Alert.show(commonFunction.getMessages('error'),commonFunction.getMessages('error'),4,null,null,errorIcon);
		}
		else{
	  		withdrawButton.enabled=false; 
	   		Alert.show(result.exception.exceptionstring+" rows updated" ,commonFunction.getMessages('success'),4,null,null,successIcon);
	   	}
	   	Mask.close();
	}
 
	/*
	 * request handler for save button
	 */
	private function resultHandler_Save(event:ResultEvent):void{
		var result:XML=event.result as XML;
		if(result.exception.exceptionstring == 'E'){
	   		mx.controls.Alert.show(commonFunction.getMessages('error'),commonFunction.getMessages('error'),4,null,null,errorIcon);
		}
		else{
	   		mx.controls.Alert.show(commonFunction.getMessages('success') ,commonFunction.getMessages('success'),4,null,null,successIcon);
	   		getStudentMarks();
	   	}
	   	Mask.close();
	 }
 
 
 
	 /**
	 * function for generating pdf on click of approve button
	 */
	 public function approveRequest(awardSheetGrid:AdvancedDataGrid):void{
	 	var headers:String="";
	 	var data:String="";
	 	var i:int=0;
	 	for each(var obj:Object in awardSheetGrid.dataProvider){
			for each(var a:AdvancedDataGridColumn in awardSheetGrid.columns){
		 		if(i==0){
					headers=headers+a.headerText+'|';
				}
				
				if(obj[a.dataField]==null){
//					data=data+"-"+";";
					data=data+commonFunction.convertNumberToWord(obj[a.dataField.substr(0,a.dataField.length-2)])+";";
				}
				else{
					data=data+obj[a.dataField]+";";
				}
			}
			data=data+"|";
			i++;
	 	}
	 	
//	 	Alert.show(headers);
//	 	Alert.show(data);
	 	var params:Object=new Object();
	 	params["entity"]=entityId;
		params["program"]=programId;
		params["branch"]=branchId;
		params["specialization"]=specializationId;
		params["semester"]=semesterId;
		params["courseCode"]=courseCode;
	 	params["courseName"]=pendingList.pendingListGrid.selectedItem.courseName;
	 	params["output"]="PDF";
	 	params["header"]=headers;
	 	params["data"]=data;
	 	params["status"]="APR";
	 	params["programCourseKey"]=programCourseKey;
	 	params["startDate"]=sessionStartDate;
		params["endDate"]=sessionEndDate;
		params["employeeCode"]=employeeCode; 
		params["previousStatus"]='SUB';//added by ankit
		params["displayType"]=displayType;//added by ankit
		params["entityName"]=entityName; //added by ankit
		params["entityTypeName"]=entityTypeName; //added by ankit
		params["programName"]=programName; //added by ankit
		params["branchName"]=branchName; //added by ankit
		params["specializationName"]=specializationName; //added by ankit
		params["semesterName"]=semesterName; //added by ankit
		Mask.show("Wait....");
		httpApproveRequestPdf.send(params);
	 	httpApproveRequest.send(params);
	 }
 
 
 private function resultHandler_ApproveRequest(event:ResultEvent):void{
	 //addes by ankit
	 var serviceResult:XML=event.result as XML;
//	 if(serviceResult.exception.exceptionstring=="success"){
		 Alert.show(commonFunction.getMessages('approvedSuccessfully'),(commonFunction.getMessages('success')),4,null,null,successIcon);
		 //addes by ankit
		 popUpGrid.approveButton.enabled=false;
		 popUpGrid.rejectButton.enabled=false;
		 var params:Object=new Object();
		 params["userId"]=userId;
		 params["employeeCode"]=employeeCode;
		 params["displayType"]=displayType;//added by ankit
		 httpPendingRequests.send(params);
		 PopUpManager.removePopUp(this);// added by ankit
		 Mask.close();
//	 }   
} 
 

	/**
	 * Function for rejecting award blank
	 */
	public function rejectRequest():void{
		//reject current and all lower level requests
		var params:Object=new Object();
	 	params["entity"]=entityId;
		params["status"]="REJ";
	 	params["programCourseKey"]=programCourseKey;
	 	params["startDate"]=sessionStartDate;
		params["endDate"]=sessionEndDate;
		params["employeeCode"]=employeeCode; 
		params["courseCode"]=courseCode;
		params["displayType"]=displayType; // added by ankit
		httpRejectRequest.send(params);
		
	}

	private function resultHandler_RejectRequest(event:ResultEvent):void{   
		popUpGrid.rejectButton.enabled=false;
	    popUpGrid.approveButton.enabled=false;
	   	var params:Object=new Object();
	 	params["userId"]=userId;
	 	params["employeeCode"]=employeeCode;
	 	params["displayType"]=displayType; //added by ankit
		httpPendingRequests.send(params);
	   	Alert.show(commonFunction.getMessages('rejectedSuccessfully'),(commonFunction.getMessages('success')),4,null,null,successIcon);   
	 }
	
	/**
	 * Function for withdrawing award blank previously submitted
	 */
	public function withdrawSheet():void{
	var params:Object=new Object();
	 	params["courseCode"]=courseCode;
		params["startDate"]=semXml.root.(name==semesterCombo.selectedLabel).startDate;
		params["endDate"]=semXml.root.(name==semesterCombo.selectedLabel).endDate;
	    params["programCourseKey"]=programCourseKey;
	    params["entityId"]=entityId;
	    params["employeeCode"]=employeeCode;  
	    params["status"]='WDW';
	    Mask.show("Wait....");
	    httpWithdrawRequest.send(params);    
	}

	/**
	 * Functions for calculating total
	 */
	public function maximumTwo(myArray:Array):int{
		//var maxValue1:Number = Math.max.apply(null, myArray);
		myArray.sort();
		var maxValue1:int =myArray.pop();
		var maxValue2:int =myArray.pop();
		var max:int=maxValue1+maxValue2;	
		return	max;
	}

	public function getTotal(row:Object,col:AdvancedDataGridColumn):String
	{
		var myArray:Array=new Array();
		var tempArray:Array=new Array();
	    for each(var obj2:Object in componentAC){
			var groupName:String=obj2.group;
			if(tempArray.indexOf(groupName)<0){	
			   	var arr:Object=new Object();
			   	var i:int=0;
			   	for each(var obj3:Object in componentAC){
					if(groupName==obj3.group){
						if(obj3.idType=='MK'){
							arr[i++]=obj3.evaluationId;
			   			}
			   		}
			   	}
				tempArray.push(groupName);
				myArray.push(arr);
			}  	
		}
			
		var total:int=0;
		for each(var ac:Object in myArray){			
			var arr1:Array=new Array();	
			for each(var o:String in ac){
				arr1.push(int(row[o]));
			}
			total=total+maximumTwo(arr1);
		}
		return	total+"";
	}